package utils;

import book.Book;
import com.bit.utils.FileUtils;
import constant.Constant;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

public class AnalyzingBook {

    public Book[] loadAllBook(String filename)throws IOException{
        String content = FileUtils.readFile(filename);
        if(content == null || content.isEmpty()){
            return null;
        }
        String[] contentPart = content.split("\n");
        Book[] books = new Book[contentPart.length];
        for (int i = 0; i < contentPart.length; i++) {
            books[i] = praseBook(contentPart[i]);
        }
        return books;
    }

    private Book praseBook(String contentPart){
        String[] parts = contentPart.split(",");
        int bookId = Integer.parseInt(parts[0]);
        String title = parts[1];
        String author = parts[2];
        String category = parts[3];
        int publishYear = Integer.parseInt(parts[4]);
        boolean isborrowed = Boolean.parseBoolean(parts[5]);
        int borrowedCount = Integer.parseInt(parts[6]);
        LocalDate shelfDate = LocalDate.parse(parts[7]);

        Book book = new Book(title, author, shelfDate, publishYear, category);
        book.setId(bookId);
        book.setIsBorrowed(isborrowed);
        book.setBorrowedCount(borrowedCount);

        return book;
    }

    public void storeAllBook(Book[] books, String fileName)throws IOException {
        int useBookLen = 0;
        for (int i = 0; i < books.length; i++) {
            if(books[i] != null){
                useBookLen++;
            }
        }

        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < useBookLen; i++) {
            Book book = books[i];
            jsonArray.append(book.toJson());
            if(i != useBookLen-1){
                jsonArray.append("\n");
            }
        }
        FileUtils.writeFile(jsonArray.toString(), fileName);

    }

    public static void main(String[] args) {
        Book[] books = new Book[5];
        books[0] = new Book("Java", "高斯林", LocalDate.now(), 1995, "编程");
        books[1] = new Book("数据结构", "大话", LocalDate.now(), 1999, "编程");
        books[2] = new Book("Mysql", "甲骨文", LocalDate.now(), 1997, "编程");

        try {
            AnalyzingBook analyzingBook = new AnalyzingBook();
            // analyzingBook.storeAllBook(books, Constant.ALL_BOOK_FILE_NAME);
            Book[] booksRet = analyzingBook.loadAllBook(Constant.ALL_BOOK_FILE_NAME);
            for (int i = 0; i < booksRet.length; i++) {
                System.out.println(booksRet[i]);
            }
        }catch (IOException e){
            throw new RuntimeException();
        }

    }
}
